package com.learn.springframework.v2.servlet;

import com.learn.springframework.annotation.*;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.*;

public class DispatcherServlet extends HttpServlet {

    /**
     * 保存application.properties
     */
    private Properties contextConfig = new Properties();
    /**
     * 保存扫描的所有类名
     */
    private List<String> classNames = new ArrayList<String>();

    /**
     * Ioc容器
     */
    private Map<String, Object> ioc = new HashMap<String, Object>();
    /**
     * 保存url和method的对应关系
     */
    private Map<String, Method> handlerMapping = new HashMap<String, Method>();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 6、根据URL 委派给具体的调用方法
        try {
            doDispatch(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
            resp.getWriter().write("500 Exception,Detail: " + Arrays.toString(e.getStackTrace()));
        }
    }

    private void doDispatch(HttpServletRequest req, HttpServletResponse resp) throws IOException, InvocationTargetException, IllegalAccessException {
        String url = req.getRequestURI();
        String path = req.getContextPath();
        url = url.replaceAll(path, "").replaceAll("/+", "/");
        if (!this.handlerMapping.containsKey(url)) {
            resp.getWriter().write("404 Not Found !!!");
            return;
        }
        Method method = this.handlerMapping.get(url);
        Map<String, String[]> parameterMap = req.getParameterMap();
        // 实参列表
        Class<?>[] parameterTypes = method.getParameterTypes();
        Object[] parameValues = new Object[parameterTypes.length];
        for (int i = 0; i < parameterTypes.length; i++) {
            Class<?> parameterType = parameterTypes[i];
            if (parameterType == HttpServletRequest.class) {
                parameValues[i] = req;
                continue;
            } else if (parameterType == HttpServletResponse.class) {
                parameValues[i] = resp;
                continue;
            } else if (parameterType == String.class) {
                Annotation[][] pa = method.getParameterAnnotations();
                for (int j = 0; j < pa.length; j++) {
                    for (Annotation a : pa[i]) {
                        if (a instanceof RequestParam) {
                            String paramName = ((RequestParam) a).value();
                            if (!"".equals(paramName.trim())) {
                                String value = Arrays.toString(parameterMap.get(paramName))
                                        .replaceAll("\\[|\\]", "")
                                        .replaceAll("\\s", ",");
                                parameValues[i] = value;
                            }
                        }
                    }
                }
            }
        }
        String beanName = toLowerFirstCase(method.getDeclaringClass().getSimpleName());
        method.invoke(ioc.get(beanName), parameValues);

    }

    /**
     * 初始化url 和method的一对一对应关系
     */
    private void doInitHandlerMapping() {
        if (ioc.isEmpty()) {
            return;
        }
        for (Map.Entry<String, Object> entry : ioc.entrySet()) {
            Class<?> clazz = entry.getValue().getClass();
            if (!clazz.isAnnotationPresent(Controller.class)) {
                continue;
            }
            // 保存写在类上面@RequestMapping("/demo")
            String baseUrl = "";
            if (clazz.isAnnotationPresent(RequestMapping.class)) {
                RequestMapping requestMapping = clazz.getAnnotation(RequestMapping.class);
                baseUrl = requestMapping.value();
            }
            // 默认获取所有的public方法
            for (Method method : clazz.getMethods()) {
                if (!method.isAnnotationPresent(RequestMapping.class)) {
                    continue;
                }
                RequestMapping requestMapping = method.getAnnotation(RequestMapping.class);
                String url = ("/" + baseUrl + "/" + requestMapping.value()).replaceAll("/+", "/");
                handlerMapping.put(url, method);
                System.out.println("Mapped " + url + "," + method);
            }
        }
    }

    /**
     * 依赖注入
     */
    private void doAutowired() {

        if (ioc.isEmpty()) {
            return;
        }
        try {
            for (Map.Entry<String, Object> entry : ioc.entrySet()) {
                // 忽略字段的修饰符、不管是private、protected、public、default,正常来讲，普通的OOP编程只能拿到public的属性
                for (Field field : entry.getValue().getClass().getDeclaredFields()) {
                    if (!field.isAnnotationPresent(Autowired.class)) {
                        continue;
                    }
                    Autowired autowired = field.getAnnotation(Autowired.class);
                    // 如果用户没有自定义beanName,默认就是根据类型注入
                    String beanName = autowired.value().trim();
                    if ("".equals(beanName)) {
                        // 获得接口的类型，作为key待会拿到这个key到ioc容器中取值
                        beanName = field.getType().getName();
                    }
                    /*if (isUpperCase(beanName.charAt(0))) {
                        beanName = toLowerFirstCase(beanName);
                    }*/
                    // 暴力访问，强吻
                    field.setAccessible(true);
                    // 相当于demoAction.demoService = ioc.get("com.learn.demo.service.DemoService")
                    field.set(entry.getValue(), ioc.get(beanName));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 判断首字母是否大写
     *
     * @param c
     * @return boolean
     */
    public boolean isUpperCase(char c) {
        return c >= 65 && c <= 90;
    }

    /**
     * 初始化IoC容器
     */
    private void doInstance() {
        if (classNames.isEmpty()) {
            return;
        }
        try {
            for (String className : classNames) {
                Class<?> clazz = Class.forName(className);

                if (clazz.isAnnotationPresent(Controller.class)) {
                    String beanName = toLowerFirstCase(clazz.getSimpleName());
                    Object instance = clazz.newInstance();
                    ioc.put(beanName, instance);
                    System.out.println("Controller :" + beanName + " , value :" + instance);
                } else if (clazz.isAnnotationPresent(Service.class)) {
                    // 1、默认类名首字母小写
                    String beanName = toLowerFirstCase(clazz.getSimpleName());
                    // 2、如果在多个包下出现了相同的类名，优先是用别名
                    Service service = clazz.getAnnotation(Service.class);
                    if (!"".equals(service.value())) {
                        beanName = service.value();
                    }
                    Object instance = clazz.newInstance();
                    ioc.put(beanName, instance);
                    // 3、如果是接口，只能初始化它的实现类
                    for (Class<?> i : clazz.getInterfaces()) {
                        // 如果一个接口存在多个实现类则抛异常
                        if (ioc.containsKey(i.getName())) {
                            throw new Exception("The " + i.getName() + " is exists,please use alies!!");
                        }
                        // 把接口类型直接当成key
                        ioc.put(i.getName(), instance);
                    }
                } else {
                    continue;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String toLowerFirstCase(String simpleName) {
        char[] chars = simpleName.toCharArray();
        // 利用了ASCII码，大写字母和小写字母相差32这个规律
        // 在java中，对char做算学运算，实际上就是对ASCII码做算学运算
        chars[0] += 32;
        return String.valueOf(chars);
    }

    /**
     * 扫描ClassPath下符合包路径规则所有的class文件
     *
     * @param scanPackage
     */
    private void doScanner(String scanPackage) {
        URL url = this.getClass().getClassLoader().getResource("/" + scanPackage.replaceAll("\\.", "/"));
        File classPath = new File(url.getFile());

        for (File file : classPath.listFiles()) {
            if (file.isDirectory()) {
                doScanner(scanPackage + "." + file.getName());
            } else {
                if (!file.getName().endsWith(".class")) {
                    continue;
                }
                // 包名.类名 比如：com.learn
                String className = (scanPackage) + "." + file.getName().replace(".class", "");
                // 实例化，要用到 Class.forName(className)
                classNames.add(className);
            }
        }
    }

    /**
     * 根据contextConfigLocation路径去classpath下找到对应文件
     *
     * @param contextConfigLocation
     */
    private void doLoadConfig(String contextConfigLocation) {
        InputStream is = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation);
        try {
            contextConfig.load(is);

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        //1、加载配置文件
        doLoadConfig(config.getInitParameter("contextConfigLocation"));

        // 2、扫描相关类
        doScanner(contextConfig.getProperty("scanPackage"));
        // ==========IoC功能======
        // 3、初始化IoC容器，将扫描到的类进行实例化，缓存IoC容器中
        doInstance();
        // ==========DI功能======
        // 4、完成依赖注入
        doAutowired();
        // 5、初始化 HandlerMapping
        doInitHandlerMapping();
        System.out.println("Spring framework is init");

    }
}
